import time
import random

from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains

from chaojiying import Chaojiying_Client


USER = ''
PWD = ''

CHAOJIYING_USER = ''
CHAOJIYING_PWD = ''

options = webdriver.ChromeOptions()
options.add_argument('start-maximized')
browers = webdriver.Chrome(options=options)
browers.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})
browers.get('https://kyfw.12306.cn/otn/resources/login.html')
time.sleep(2)
browers.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click()
# 截屏`
browers.save_screenshot('main.png')
image_tag = browers.find_element_by_xpath('//*[@id="J-loginImg"]')
# 图片左下角坐标
location = image_tag.location
# 图片宽和高
size = image_tag.size
info = (location['x'], location['y'], location['x']+size['width'], location['y']+size['height'])

i = Image.open('./main.png')
# 截取图片中指定坐标的图片，坐标为元组
img = i.crop(info)
img.save('code.png')


def auth_chaojiying(img_path, img_type):
    chaojiying = Chaojiying_Client(CHAOJIYING_USER, CHAOJIYING_PWD, '907084')
    im = open(img_path, 'rb').read()
    result = chaojiying.PostPic(im, img_type)['pic_str']
    new_list = []
    outer = result.split('|')
    for inner in outer:
        new_list.append(inner.split(','))
    return new_list


xx = auth_chaojiying('code.png', '9004')
print(xx)
user = browers.find_element_by_id('J-userName')
user.click()
user.send_keys(USER)
time.sleep(1)
pwd = browers.find_element_by_id('J-password')
pwd.click()
pwd.send_keys(PWD)
for xy in xx:
    x = int(xy[0])
    y = int(xy[1])
    ActionChains(browers).move_to_element_with_offset(image_tag, xoffset=x, yoffset=y).click().perform()
    time.sleep(1)
browers.find_element_by_id('J-login').click()
time.sleep(2)
tag = browers.find_element_by_id('nc_1_n1z')
action = ActionChains(browers)
action.click_and_hold(tag)
for i in range(15):
    action.move_by_offset(random.randint(25, 30), 0).perform()